/**
 * 
 */
package com.etrans.web.gps.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: DateUtil.java<／p>
 * <p>Description: <／p>
 * <p>Copyright: Copyright (c) 2007<／p>
 * <p>Company: E-trans<／p>
 * 
 * @author R.Lao
 * @date 2017年6月13日
 * @time 上午8:59:08
 * @version 1.0
 */
public class DateUtil {

	/**
	 * 获取指定时间戳(毫秒格式)
	 */
	public static String getMillFormatDateTime(long _value) {
		return getMillFormatDateTime(new Date(_value));
	}

	/**
	 * 获取指定日期(毫秒格式)
	 */
	public static String getMillFormatDateTime(Date _value) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS");
		return sdf.format(_value);
	}

	/**
	 *  根据秒获取时分
	 *  
	 * @param second 秒
	 * @return String
	 */
	public static String getHMBySecond(int second){
		if(second/3600>=1){
			int h = second/3600;
			int m = second%3600/60;
			int s = second%60;
			return ""+h+"时"+(m>0?""+m+"分":"")+(s>0?""+s+"秒":"");
		}else{
			int m = second%3600/60;
			int s = second%60;
			return m+"分"+(s>0?""+s+"秒":"");
		}
	}
	
	/**
	 * <title>getStringToDate</title>
	 * 
	 * @param date
	 * @return Date
     */
	public static Date getStringToDate(String date){
		try {
			if(null!=date){
				return DateUtil.getStrToDate(date);
			}else{
				return DateUtil.getPreviousDayDate();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * getDateToString
	 * 
	 * @param _value Date
	 * @param  formate  String
	 * @return String
     */
	public static String getDateToString(Date _value,String formate) {
		if(null==formate)formate="yyyy-MM-dd";
		SimpleDateFormat sdf = new SimpleDateFormat(formate);
		return sdf.format(_value);
	}
	/**
	 * getDateToString
	 * 
	 * @param _value Date
	 * @param  formate  String
	 * @return String
     */
	public static String getDateToString(Date _value) {
		return getDateToString(_value,null);
	}

	/**
	 * <p>
	 * 	Date转时间型String
	 * </p>
	 * 
	 * @param runTime Date
	 * @param formate String
	 * @return _value String
	 */
	public static String getDateTimeString(Date runTime,String formate) {
		if(null==formate)formate="yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(formate);
		return sdf.format(runTime);
	}
	
	/**
	 * 从long型日期转String类型
	 * 
	 * @param date
	 * @param formate
	 * @return String
	 */
	public static String getDateFromLong(long date,String formate){
		Date _date = new Date(date);
		if(null==formate)formate="yyyy-MM-dd";
		SimpleDateFormat sdf = new SimpleDateFormat(formate);
		return sdf.format(_date);
	}
	
	/**
	 * getDate 
	 * 
	 * @param _value
	 * @return
	 */
	public static Date getDate(Date _value) {
		String time = getDateTimeString(_value,null);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return sdf.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * <title>获取前一天的日期</title>
	 * <code>getPreviousDayDate("yyyy-MM-dd")</code>
	 *
	 * @return Date date
	 */
	public static Date getPreviousDayDate(){
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1); //得到前一天
		Date date = calendar.getTime();
		return date;
	}
	/**
	 * <title>获取当前周</title>
	 * <code>getDayOfWeek("yyyy-MM-dd")</code>
	 *
	 * @return Date date
	 */
	public static int getDayOfWeek(Date date){
		Calendar calendar = Calendar.getInstance();
		calendar.setFirstDayOfWeek(Calendar.MONDAY);
		calendar.setTime(date);
		return calendar.get(Calendar.WEEK_OF_YEAR);
	}
	/**
	 * <title>获取前N天的日期</title>
	 * <code>getPreviousDayDate("yyyy-MM-dd")</code>
	 *
	 * @return Date date
	 */
	public static Date getPreviousDayDate(int pre){
		Calendar calendar = Calendar.getInstance();
		
		calendar.add(Calendar.DATE, -(pre)); //得到前一天		
		Date date = calendar.getTime();
		return date;
	}

	/**
	 * getStrToDate
	 * @param dateString
	 * @return
	 * @throws ParseException
     */
	public static Date getStrToDate(String dateString) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = sdf.parse(dateString);
		return  date;
	}

	  /**
     * 计算两个日期之间相差的秒数
     * @param startdate 较小的时间 
     * @param enddate 较大的时间 
     * @return 相差秒数 
     * @throws ParseException
     */
    public static int SecondsBetween(String starttime,String endtime)  {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date startdate;
		try {
			startdate = sdf.parse(starttime);
			Date enddate = sdf.parse(endtime);
			Calendar cal = Calendar.getInstance();
			cal.setTime(startdate);
			long time1 = cal.getTimeInMillis();
			cal.setTime(enddate);
			long time2 = cal.getTimeInMillis();
			long between_days = (time2 - time1) / 1000;
			return Integer.parseInt(String.valueOf(between_days));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}
	} 
    
 
    /**
     * 
     * @param starttime
     * @param endtime
     * @return
     */
    public static boolean isSameDate(String starttime,String endtime){
    	return starttime.subSequence(0, 10).equals(endtime.substring(0, 10)); 
    }
    
     public static  String getStandardDateStr(Date start) {

        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start);

        
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

        return sdf.format(tempStart.getTime());
    }
    
    public static  List<String> getBetweenDates(Date start, Date end) {
        List<String> result = new ArrayList<String>();
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start);
        tempStart.add(Calendar.DAY_OF_YEAR, 1);
        
        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

        if(sdf.format(start).equals(sdf.format(end))){
        	result.add(sdf.format(start));
        }else{
        	result.add(sdf.format(start));
            while (tempStart.before(tempEnd)) {
                result.add(sdf.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
            result.add(sdf.format(end));
        }
        
        return result;
    }
 	/**
	 * 
	 * @param dateString 字符日期格式
	 * @param format 转换的格式
	 * @return
	 * @throws ParseException
	 */
	public static Date getStrToDateFormat(String dateString,String format) throws ParseException {
		if(format==null){
			format="yyyy-MM-dd hh:mm:ss";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date date = sdf.parse(dateString);
		return date;
	}
	
	public static void main(String[] args) throws ParseException {
//		System.out.println(DateUtil.getStrToDate("2017-03-01"));
//		String dateStr = "2017-07-02 16:01:00";
//		String formate="yyyy-MM-dd HH:mm:ss";
//		Date gpstime = new SimpleDateFormat(formate).parse(dateStr);
//		System.out.println(compare(gpstime.getTime()));
//		String s = DateUtil.getHMBySecond(3600);
		System.out.println(getDates("2017-08-20","2017-09-21"));
	}
	
	/**
	 * 比较时间是否在业务允许范围内
	 */
	@SuppressWarnings("deprecation")
	public static boolean compare(Date alarmTime){
		Date date = new Date();
		alarmTime.setMinutes(alarmTime.getMinutes() + 10);
		return alarmTime.after(date);
	}
	
	public static boolean compare(long time){
		return compare(new Date(time));
	}
	
	/**
	 * @category 获取给定时间段的每一天日期的格式化字符串
	 * @author RenweiWu
	 * @param startDate 开始日期  yyyy-MM-dd
	 * @param endDate 结束日期  yyyy-MM-dd
	 * @return  List<String> 日期格式化的String
	 */
	 public static List<String> getDates(String startDate,String endDate){  
		  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		  Date dBegin=null;  
		  Date dEnd=null;
			try {
				dBegin = sdf.parse(startDate);
				dEnd = sdf.parse(endDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
		  List<String> StringDate = new ArrayList<String>(); 
		  StringDate.add(sdf.format(dBegin));
		  Calendar calBegin = Calendar.getInstance();  
		  calBegin.setTime(dBegin);  // 使用给定的 Date 设置此 Calendar 的时间  
		  Calendar calEnd = Calendar.getInstance();  
		  calEnd.setTime(dEnd);   // 使用给定的 Date 设置此 Calendar 的时间  
		  while (dEnd.after(calBegin.getTime())){    // 测试此日期是否在指定日期之后  
			   calBegin.add(Calendar.DAY_OF_MONTH, 1);  // 根据日历的规则，为给定的日历字段添加或减去指定的时间量  
			   StringDate.add(sdf.format(calBegin.getTime()));  
		  	}  
		  return StringDate;  
	 }
	 
		/**
		 * <title>获取前N个月的日期</title>
		 * <code>getPreviousDayDate("yyyy-MM")</code>
		 * @return Date date()
		 */
		public static Date getPreviousMonthDate(int pre){
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.MONTH, -pre); //得到前一天
			Date date = calendar.getTime();
			return date;
		}
		public static Date getPreviousWeekDate(){
	        // 当前日期
	        Calendar calendar = Calendar.getInstance();
	        // 调整到上周
	        calendar.add(Calendar.WEDNESDAY, -1);
	        // 调整到上周1
	        calendar.set(Calendar.DAY_OF_WEEK, 2);
	     
			return calendar.getTime();
		}
		public static Date getPreviousWeekSunDateDate(){
	        // 当前日期
	        Calendar calendar = Calendar.getInstance();
	        // 调整到上周
	        calendar.add(Calendar.WEDNESDAY, -1);
	        // 调整到上周1
	        calendar.set(Calendar.DAY_OF_WEEK, 2);
	        calendar.add(Calendar.DAY_OF_WEEK, 6);
			return calendar.getTime();
		}
		/**
		 * <title>获取给定时间的星期数（第几个星期）</title>
		 * <code>getWeekNum("WW")</code>
		 * @return int
		 */
		public static int getWeekNum(Date date){
			Calendar calendar = Calendar.getInstance(); 
			calendar.setTime(date); 
			return calendar.get(Calendar.WEEK_OF_YEAR);
		}
		
		/**
		 * @category 获取给定年份的第几周的周一和 周日 
		 * @author RenweiWu
		 * @param year 年份
		 * @param week 第几周
		 * @return Map<String,Object>  key: Monday周一的日期;  Sunday周日的日期;  year传入的年份;  week传入的周数;
		 * @author RenweiWu
		 */
	    public  static Map<String,Object> getYearAndWeekByDate(int year,int week) {
	        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式  
	    	Map<String,Object> map = new HashMap<String,Object>();
			Calendar cald = Calendar.getInstance();
			cald.set(Calendar.YEAR, year); // 2016年
			cald.set(Calendar.WEEK_OF_YEAR,week); // 设置为2016年的第10周
			cald.set(Calendar.DAY_OF_WEEK, 2); // 1表示周日，2表示周一，7表示周六
			Date date = cald.getTime();
	        Calendar cal = Calendar.getInstance();  
	        cal.setTime(date);  
	       //判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了  
	        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);//获得当前日期是一个星期的第几天  
	        if(1 == dayWeek) {  
	            cal.add(Calendar.DAY_OF_MONTH, -1);  
	        }  
	        cal.setFirstDayOfWeek(Calendar.MONDAY);//设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一  
	        int day = cal.get(Calendar.DAY_OF_WEEK);//获得当前日期是一个星期的第几天  
	        cal.add(Calendar.DATE, cal.getFirstDayOfWeek()-day);//根据日历的规则，给当前日期减去星期几与一个星期第一天的差值   
	        String imptimeBegin = sdf.format(cal.getTime());  
	        map.put("Monday",imptimeBegin);
	        cal.add(Calendar.DATE, 6);  
	        String imptimeEnd = sdf.format(cal.getTime());  
	        map.put("Sunday",imptimeEnd);
	        map.put("year",year);
	        map.put("week",week);
	        return map;
	   } 
}
